import { Destroyable, react, reactJson, Event, track, HasOwner, reactJsonWithUndefined } from "xbsj-xe2/dist-node/xe2-base-utils";
import { MyProjectManager } from "../MyProjectManager";
import { Child, TransformedChild } from '@/scripts/dataTypes/interface'
import { ObjResettingWithEvent, SceneObject, Viewer } from 'xbsj-xe2/dist-node/xe2-base-objects';
import { ESRtsFeatureEditing } from "../esobjs/ESRtsFeatureEditing";
import { getsceneObjNumfromSceneTree } from "../utils";
import { ElMessage } from "element-plus";
import { ESRtsEexturedPolygon } from "../esobjs/ESRtsEexturedPolygon";
import { ESRtsPolygon } from "../esobjs/ESRtsPolygon";

function isNumber(value: any): boolean {
    return typeof value === 'number' && !isNaN(value);
}
class PickResettting extends Destroyable {
    constructor(featureEdit: FeatureEdit, owner: MyProjectManager) {
        super();
        const eSRtsTileset = owner.cimrtsManager.eSRtsTileset
        const viewer = owner.activeViewer

        if (!viewer) return;
        this.dispose(viewer.clickEvent.don(async e => {

            if (!e.screenPosition) return;
            // 拾取
            const obj = await eSRtsTileset.pickFeature(viewer, e.screenPosition)
            // console.log("obj", obj);

            // 选中的id
            const currentFeatureId = obj?.featureId

            // pick选中内置属性
            const pickInnerFields = obj?.pickInnerFields
            if (pickInnerFields) {
                for (const key in pickInnerFields) {
                    pickInnerFields[key] = typeof pickInnerFields[key] === 'bigint' ? pickInnerFields[key].toString() + 'n' : pickInnerFields[key]
                }
            }
            if (this.isDestroyed() || !currentFeatureId) return;


            // 设置内置属性
            featureEdit.innerFields = Object.entries(pickInnerFields).map((e: any) => {
                return {
                    key: e[0],
                    value: e[1]
                }
            })

            const property = await eSRtsTileset.getFeatureProperty(currentFeatureId) as any;
            const param = property.geometry.param

            let sceneObject: ESRtsFeatureEditing | ESRtsPolygon | ESRtsEexturedPolygon | undefined = undefined

            // 绘制对象 
            if (param) {
                const json = JSON.parse(param)
                // scenetree上面存在
                if (!(owner.cimrtsSceneTreeWrapper?.getTreeItemFromSceneObjId(json.id))) {
                    sceneObject = owner.createSceneObjectFromJson(json) as ESRtsFeatureEditing | ESRtsPolygon
                    //隐藏原来大的中的feature
                    eSRtsTileset.setFeatureVisable('id', [{ value: currentFeatureId, visable: false }]);
                    sceneObject.d(() => { eSRtsTileset.setFeatureVisable('id', [{ value: currentFeatureId, visable: true }]) });

                    sceneObject.uiShowprops = property.allFields.map((e: any) => {
                        return {
                            featureClassName: e.featureClassName,
                            fields: e.fields.map((f: any) => {
                                return {
                                    key: f.name,
                                    type: f.type,
                                    value: f.type != "Double" ? f.value : (isNumber(f.value) ? Number(f.value.toFixed(3)) : "")
                                }
                            })
                        }
                    })
                    sceneObject.datasetName = property.datasetName
                    sceneObject.featureId = currentFeatureId
                    // @ts-ignore
                    sceneObject.geometryId = property.geometry.id
                    // @ts-ignore
                    sceneObject.create = false

                    const treeItem = owner.createdTreeItem(owner.cimrtsSceneTreeWrapper)
                    treeItem.sceneObject = sceneObject;
                    treeItem.name = sceneObject.name
                    owner.cimrtsSceneTreeWrapper?.uiTree.clearAllSelectedItems()
                    treeItem.uiTreeObject.selected = true

                    owner.propSceneTree = {
                        createOrEdit: 'edit',
                        propType: "waterMend",
                        sceneObject: sceneObject,
                    }
                } else {
                    sceneObject = owner.getSceneObjectById(json.id) as ESRtsFeatureEditing
                    owner.propSceneTree = {
                        createOrEdit: 'edit',
                        propType: "waterMend",
                        sceneObject: sceneObject,
                    }
                }



            } else {
                // scenetree上面存在
                if (!(owner.cimrtsSceneTreeWrapper?.getTreeItemFromSceneObjId(currentFeatureId))) {
                    sceneObject = owner.createSceneObject(ESRtsFeatureEditing, currentFeatureId) as ESRtsFeatureEditing
                    await sceneObject.init(eSRtsTileset, currentFeatureId)

                    const treeItem = owner.createdTreeItem(owner.cimrtsSceneTreeWrapper)
                    treeItem.sceneObject = sceneObject;
                    sceneObject.editing = true
                    const name = featureEdit.innerFields.find((e: any) => e.key === "name")?.value
                    const newName = "编辑要素_" + (name ? name : (sceneObject.id ? sceneObject.id : ""))
                    const num = getsceneObjNumfromSceneTree(sceneObject.typeName, owner.cimrtsSceneTreeWrapper)
                    treeItem.name = `${newName}(${num})`
                    owner.cimrtsSceneTreeWrapper?.uiTree.clearAllSelectedItems()
                    treeItem.uiTreeObject.selected = true

                    owner.propSceneTree = {
                        createOrEdit: 'edit',
                        propType: "featureEdit",
                        sceneObject: sceneObject,
                    }
                } else {
                    sceneObject = owner.getSceneObjectById(currentFeatureId) as ESRtsFeatureEditing

                    owner.propSceneTree = {
                        createOrEdit: 'edit',
                        propType: "featureEdit",
                        sceneObject: sceneObject,
                    }
                }

            }
        }))
    }
}

export class FeatureEdit extends HasOwner<MyProjectManager> {

    // 开启拾取
    private _enablePick = this.dv(react<boolean>(false));
    get enablePick() { return this._enablePick.value; }
    get enablePickChanged() { return this._enablePick.changed; }
    set enablePick(value: boolean) { this._enablePick.value = value; }

    // 点击编辑事件
    private _editEvent = this.dv(new Event());
    get editEvent() { return this._editEvent; }

    // 拾取处理
    private _pickResettting = this.dv(new ObjResettingWithEvent(this.enablePickChanged, () => {
        if (!this.enablePick) return undefined;
        return new PickResettting(this, this.owner);
    }))
    get pickResettting() { return this._pickResettting; }


    // 内置属性
    private _innerFields = this.dv(reactJson<any>([]));
    get innerFields() { return this._innerFields.value; }
    get innerFieldsChanged() { return this._innerFields.changed; }
    set innerFields(value: any) { this._innerFields.value = value; }

    init() {
        this.enablePick = true
    }
    clear() {
        this.enablePick = false
        this.innerFields = []
    }

    constructor(private _tileServiceName: string, owner: MyProjectManager) {
        super(owner);
    }
}







